/* 
 * Page Initialization
 *  
 */
function initialize() {
	$.getJSON('CalendarServlet', function(data) {
		var calTableContent = [];
		var d = new Date();
		// Table head
		calTableContent
				.push('<thead><tr id="tableheader"><th colspan="3">Today: ' + d
						+ '</th></tr></thead>');

		// Table body
		calTableContent.push('<tbody>');
		calTableContent
				.push('<tr><th>Date</th><th>Time</th><th>Content</th></tr>');
		$.each(data, function() {
			calTableContent.push('<tr id="' + this.id + '"><td>'
					+ $.datepicker.parseDate('M dd, yy', this.date)
					+ '</td><td>' + this.time + '</td><td>' + this.content
					+ '</td></tr>');
			// Assign last item date to the hidden value as mark
			saveLastCalDate(this.date);
		});
		calTableContent.push('</tbody>');

		// Table foot
		calTableContent.push('<tfoot><tr id="tablefoot"><th colspan="3"><a href="#" onclick="more();">More...</a></th></tr></tfoot>');

		$('<table/>', {
			'class' : 'calendar',
			html : calTableContent.join('')
		}).appendTo('div#calendarTable');
		// If Last item date no value, assgin today's date
		if($('#last_date').val() == "")
			$('#last_date').val(new Date());
	});
	
	// Initialize jQuery date picker
	$("#datepicker").datepicker();
};

/**
 * Save last item date to the hidden value as mark
 * 
 * @param date
 */
function saveLastCalDate(date) {
	$('#last_date').val($.datepicker.parseDate('M dd, yy', date));
};

/**
 * More link event
 * 
 */
function more() {
	//alert($('#last_date').val());
	var date = $.datepicker.parseDate('D M dd yy', $('#last_date').val());
	var d = $.datepicker.formatDate('yy-mm-dd', date);
	//alert(d);
	$.getJSON('CalendarServlet?action=m&date=' + d, function(data) {
		var calTableContent = [];
		$.each(data, function() {
			calTableContent.push('<tr id="' + this.id + '"><td>'
					+ $.datepicker.parseDate('M dd, yy', this.date)
					+ '</td><td>' + this.time + '</td><td>' + this.content
					+ '</td></tr>');
			// Assign last item date to the hidden value as mark
			saveLastCalDate(this.date);
		});
		
		//alert('OK');
		
		// Append new record to calendar table body
		$(calTableContent).appendTo('table.calendar tbody');
	});
};